import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { Comment } from '../types/Article'
import axios from '../axios';

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem('token'));
  const userID = ref<number | null>(null);
  const level = ref<number | null>(null); // 👈 新增 level 状态

  const isAuthenticated = computed(() => !!token.value);

  const login = async (username: string, password: string) => {
  try {
    const response = await axios.post('/api/auth/login', { username, password });
    if (response.data.token) {
      token.value = response.data.token;
      userID.value = response.data.user_id;

      // ✅ 新增：从登录接口直接获取 level
      if (response.data.level !== undefined) {
        level.value = parseInt(response.data.level.toString());
      }

      localStorage.setItem('token', token.value || '');
    }

    await fetchUserInfo(); // 仍然保留用于补充其他信息

    return response.data;
  } catch (error) {
    console.error('Login error:', error);
    throw error;
  }
};

  const register = async (username: string, password: string) => {
    try {
      const response = await axios.post('/api/auth/register', { username, password });
      token.value = response.data.token;
      localStorage.setItem('token', token.value || '');

      await fetchUserInfo();

      return response.data;
    } catch (error) {
      console.error('Register error:', error);
      throw error;
    }
  };

  const logout = () => {
    token.value = null;
    userID.value = null;
    localStorage.removeItem('token');
    localStorage.removeItem('userID');
    level.value = null; // 👈 清空 level 数据
  };

  const fetchUserInfo = async () => {
    if (!token.value) return;
    try {
      const response = await axios.get('/api/users/me');
      console.log('接口 /api/users/me 返回数据:', response.data);

      const uid = response.data.ID;

      if (uid !== undefined && uid !== null) {
        userID.value = parseInt(uid.toString());
        localStorage.setItem('userID', userID.value.toString());
      } else {
        console.warn('API /users/me 返回中未找到 ID 字段');
      }

      // ✅ 使用新增的 level ref
      if (response.data.level !== undefined) {
        level.value = parseInt(response.data.level.toString());
      }

    } catch (error) {
      console.error('Failed to fetch user info:', error);
    }
  };

  // 初始化时尝试从 localStorage 加载 userID 或请求接口
  const storedUserID = localStorage.getItem('userID');
  if (storedUserID) {
    userID.value = parseInt(storedUserID);
  }

  if (token.value && !userID.value) {
    fetchUserInfo();
  }

  return {
    token,
    userID,
    level, // 👈 暴露 level 状态
    isAuthenticated,
    login,
    register,
    logout,
    fetchUserInfo
  };
});
export const useCommentStore = defineStore('comments', {
  state: () => ({
    commentsMap: {} as Record<string, Comment[]>
  }),
  actions: {
    addComments(postId: string, comments: Comment[]) {
      this.commentsMap[postId] = comments
    },
    getComments(postId: string) {
      return this.commentsMap[postId] || []
    }
  }
})